package com.gk.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gk.study.Vo.CourseTeacherVO;
import com.gk.study.common.APIResponse;
import com.gk.study.common.CourseStatus;
import com.gk.study.entity.Course;
import com.gk.study.entity.Score;
import com.gk.study.entity.Thing;
import com.gk.study.mapper.ScoreMapper;
import com.gk.study.service.CourseService;
import com.gk.study.service.ThingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    ThingService thingService;

    @Autowired
    ScoreMapper scoreMapper;

    // 获取用户的课程列表（根据状态过滤）
    @GetMapping("/my")
    public APIResponse getMyCourses(
            @RequestParam Long userId,
            @RequestParam(required = false) CourseStatus status
    ) {
        List<Course> courses = courseService.getCoursesByUser(userId, status);

        // 评价状态
        courses.forEach(course -> {
            boolean hasEvaluation = scoreMapper.existsByCourseAndUser(course.getId(), userId);
            course.setHasEvaluation(hasEvaluation);
        });

        return APIResponse.success("查询成功", courses);
    }

    // 取消课程
    @PostMapping("/{courseId}/cancel")
    public APIResponse cancelCourse(
            @PathVariable Long courseId,
            @RequestParam Long userId
    ) {
        courseService.cancelCourse(courseId, userId);
        return APIResponse.success("取消成功");
    }

    // 确认课程完成
    @PostMapping("/{courseId}/complete")
    public APIResponse completeCourse(
            @PathVariable Long courseId,
            @RequestParam Long userId
    ) {
        courseService.completeCourse(courseId, userId);
        return APIResponse.success("确认完成");
    }


    @GetMapping("/teacher")
    public APIResponse getTeacherCourses(
            @RequestParam Long userId, // 当前教师登录后的user.id
            @RequestParam(required = false) CourseStatus status
    ) {
        // 1. 根据userId查询教师信息
        Thing teacher = thingService.getThingByUserId(String.valueOf(userId));
        if (teacher == null) {
            return APIResponse.error("教师信息不存在");
        }

        LambdaQueryWrapper<Course> query = new LambdaQueryWrapper<>();
        query.eq(Course::getTeacherId, teacher.getId())
                .eq(status != null, Course::getStatus, status)
                // 已完成的课程需要两个确认标记都为true
                .apply(status == CourseStatus.COMPLETED,
                        "(student_confirmed = 1 AND teacher_confirmed = 1)");

        // 2. 查询课程数据
        List<CourseTeacherVO> courses = courseService.getTeacherCourses(teacher.getId(), status);

        // 3. 处理时间格式
        courses.forEach(course -> {
            course.setFormattedStartTime(course.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd ")));
            course.setFormattedEndTime(course.getEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd ")));
        });

        return APIResponse.success("查询成功", courses);
    }

    @PostMapping("/updateStatus")
    public APIResponse updateStatus(
            @RequestParam Long courseId,
            @RequestParam String status
    ) {
        Course course = courseService.getById(courseId);
        if (course == null) {
            return APIResponse.error("课程不存在");
        }

        // 直接更新状态（无权限验证）
        course.setStatus(CourseStatus.valueOf(status));
        courseService.updateById(course);

        return APIResponse.success("操作成功");
    }


    // 家长端确认完成
    @PostMapping("/studentConfirm/{courseId}")
    public APIResponse studentConfirm(
            @PathVariable Long courseId,
            @RequestParam Long userId
    ) {
        Course course = courseService.getById(courseId);
        // 验证学生身份
        if (!course.getStudentId().equals(userId)) {
            return APIResponse.error("无操作权限");
        }
        course.setStudentConfirmed(true);
        checkCompletion(course);
        return APIResponse.success("学生确认成功");
    }

    // 教师确认完成
    @PostMapping("/teacherConfirm/{courseId}")
    public APIResponse teacherConfirm(
            @PathVariable Long courseId,
            @RequestParam Long userId
    ) {
        Course course = courseService.getById(courseId);
        // 验证教师身份
        Thing teacher = thingService.getThingByUserId(userId.toString());
        if (!course.getTeacherId().equals(teacher.getId())) {
            return APIResponse.error("无操作权限");
        }
        course.setTeacherConfirmed(true);
        checkCompletion(course);
        return APIResponse.success("教师确认成功");
    }

    // 检查是否完成
    private void checkCompletion(Course course) {
        if (course.getStudentConfirmed() && course.getTeacherConfirmed()) {
            course.setStatus(CourseStatus.COMPLETED);
        }
        courseService.updateById(course);
    }

    @GetMapping("/unrated")
    public APIResponse getUnratedCourses(@RequestParam Long userId) {
        List<Course> courses = courseService.getUnratedCompletedCourses(userId);
        return APIResponse.success("查询成功", courses);
    }

    // 评价提交接口
    @PostMapping("/submitEvaluation")
    public APIResponse submitEvaluation(
            @RequestBody Score score,
            @RequestParam Long userId // 正确接收URL参数
    ) {
        score.setUserId(userId);
        courseService.submitEvaluation(score);
        return APIResponse.success("评价提交成功");
    }


}